﻿using EWC.Core.Util.CustomException;
using EWC.Core.WebApi.Filters;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EWC.Core.Util.Middleware.CustomExceptionMid
{
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionMiddleware> _logger;

        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                await HandleExceptionAsync(context, ex);
            }
        }

        private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";
            var result = new ResponseResult<object>
            {
                Code = EResultCode.Error,
                Message = "系统异常",
            };
            if (exception is UserFriendlyException)
            {
                result.Data = exception.Message;
                result.Message = "业务异常";
            }

            var setting = new JsonSerializerSettings();
            setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
            await context.Response.WriteAsync(JsonConvert.SerializeObject(result, setting), Encoding.UTF8);
            //  var result = JsonConvert.SerializeObject(new { error = exception.Message });
            // await context.Response.WriteAsync("系统错误");
        }
    }
}
